<template>
    
    <!-- 组件的模板 -->
    <div class="weui-cells__title bg_color" v-if="desc">{{desc}}</div>
    <div id="items">
        <div v-for="item in reportInfo.info">
            
            <div class='border-top' v-if="item.type === 'Date'">
                <formdate
                            :title="item.info.title" 
                            :tip="item.info.tip" 
                            :date.sync="item.info.value"
                            :required="item.info.required"
                            :isvalid.sync="item.isValid"
                ></formdate>
            </div>
            <div class='border-top' v-if="item.type === 'SingleText'">
                <formsingle 
                            :iosstyle.sync="isiosStyle"
                            :title="item.info.title" 
                            :tip="item.info.tip" 
                            :val.sync="item.info.value"
                            :required="item.info.required"
                            :isvalid.sync="item.isValid"
                            :isscan="item.info.scanQRCode"
                            :formid.sync="item.id"
                ></formsingle>
            </div>
            <div class='border-top' v-if="item.type === 'TextArea'">
                <formtextarea 
                            :title="item.info.title" 
                            :tip="item.info.tip" 
                            :val.sync="item.info.value"
                            :required="item.info.required"
                            :isvalid.sync="item.isValid"
                ></formtextarea>
            </div>
            <div class='border-top' v-if="item.type === 'Number'">
                <formnumber
                            :title="item.info.title"
                            :tip="item.info.tip"
                            :val.sync="item.info.value"
                            :required="item.info.required"
                            :isvalid.sync="item.isValid"
                ></formnumber>
            </div>
            <div class='border-top' v-if="item.type === 'Select'">
                <formselect 
                            :title="item.info.title" 
                            :tip="item.info.tip" 
                            :val.sync="item.info.value"
                            :opts="item.info.options"
                            :required="item.info.required"
                            :isvalid.sync="item.isValid"
                ></formselect>
            </div>
            <div class='border-top' v-if="item.type === 'Location'">
                <div class="comp-wrap" style="position: relative">
                    <div class="weui-cells__title black">{{item.info.title}}<span v-if="item.info.required == 1" class="required_icon"> (必填)</span></div>
                    <div class="feedback-box" @click="feedBack">
                        <img src="../../static/imgs/feedback.png" alt="" class="feedback-icon">
                        <span class="feedback-text">我要反馈</span>
                    </div>
                    <div class="weui-cells__tips">{{item.info.tip}}</div>
                    <div class="weui-cells">
                        <div class="weui-cell padding">
                                <template v-if="item.info.value.lat && item.info.value.lng">
                                    <template v-if="item.info.value.addr == ''">
                                        <div class="addr_name">{{'(' + item.info.value.lng + ',' + item.info.value.lat + ')'}}</div>
                                    </template>
                                    <template v-else>
                                        <div class="addr_name">{{item.info.value.name}}</div>
                                        <div class="addr_detail">{{item.info.value.addr}}</div>
                                    </template>
                                </template>
                                <template v-else>
                                    <div class="addr_name">定位中...</div>
                                </template>
                            <div class="location_tip">
                               <p class="relacation" @click="getLocation">重新定位</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class='border-top' v-if="item.type === 'Imageview'">
                <div class="comp-wrap">
                    <!-- <imageview :title="item.info.title"></imageview> -->
                    <div class="weui-cells weui-cells_form left_0">
                        <div class="weui-cell" style="padding:0px;">
                            <div class="weui-cell__bd">
                                <div class="weui-uploader">
                                    <div class="bg_f2">
                                        <div class="weui-uploader__hd pad-lr black">
                                            <p class="weui-uploader__title isTitle">{{item.info.title}}
                                                <span v-if="item.info.required == 1 && item.info.check_guide.min != ''" class="required_icon"> (请至少上传{{item.info.check_guide.min}}张图片)</span>
                                                <span v-if="item.info.required == 1 && item.info.check_guide.min == ''" class="required_icon"> (请至少上传1张图片)</span>
                                            </p>
                                            
                                        </div>
                                        <div class="weui-cells__tips pad-left-0 pad-lr">{{item.info.tip}}</div>
                                    </div>
                                    <div class="weui-uploader__bd pad-lr pad-tb" style="position:relative;">
                                        <ul class="weui-uploader__files" id="uploaderFiles">
                                            <li class="weui-uploader__file img" 
                                                v-for="imgurl in item.info.thumb_image_value" track-by="$index"
                                                :style="'background-image:url('+imgurl+')'"
                                                @click="pictureOperationDialog($parent.$index, $index)"
                                                >
                                            </li>
                                        </ul>
                                        <div class="weui-uploader__input-box">
                                            <input id="uploaderInput" class="weui-uploader__input" type="" readonly @click="selectImage($index)" />
                                        </div>
                                        <div class="weui-uploader__info img_cont">{{item.info.value.length}}/20</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    let ajaxEnd = true
    /**
     *  引入工具类库 或 Native API
     *  example : import widget from 'gapi/widget'
     */
    import widget from 'gapi/widget.js'
    import clientUi from 'gapi/clientUi.js'
    import * as util from 'js/util.js'
    import commonPage from 'clientApi/commonPage.js'
    import location from 'gapi/location.js'
    import cache from 'gapi/cache.js'
    import KCApiApp from 'clientApi/KCApiApp.js'
    import teamApi from 'clientApi/teamApi.js'

    /**
     *  引入组件 以及 组件接口(Action)
     *  example : import Somecomponents from 'components/Somecomponents/Somecomponents'
     */
    import Formsingle from 'components/Formsingle/Formsingle'
    import Formtextarea from 'components/Formtextarea/Formtextarea'
    import Formnumber from 'components/Formnumber/Formnumber'
    import Formselect from 'components/Formselect/Formselect'
    import Formdate from 'components/Formdate/Formdate'
    import Location from 'components/Location/Location'
    import { getLoc } from 'components/Location/LocationGetters'
    import Imageview from 'components/Imageview/Imageview'
    import { getImageArray } from 'components/Imageview/ImageviewGetters'
    import clientUtil from 'clientApi/util' 

    /**
     *  组件实例对象
     */
    export default {
        components: {
            Formsingle,
            Formtextarea,
            Formnumber,
            Formselect,
            Formdate,
            Location,
            Imageview
        },
        data: function(){
            return{
                reportInfo: {
                    team_id: 0,
                    project_id: 0,
                    form_id: 0,
                    info: []
                },
                par_index: 0,
                desc: '',
                isiosStyle:true,
                failNum: 0,
                // isTip: true
            }
        },
        vuex: {
            getters: {
                getLoc,
                getImageArray
            },
            actions: {

            }
        },
        methods: {
            /**
             * 初始化
             * @method init
             * @public
             * @return {Null} void
             */
            init (){
                //ios和安卓样式不兼容
                if(clientUtil.OS() =='ios'){
                    this.isiosStyle = true
                }else{
                    this.isiosStyle = false
                }
                this.reportInfo.form_id = util.getUrddataString('form_id')
                commonPage.loadPageStatus('loading')
                cache.getCache('user_info', (data) => {
                    // alert(JSON.stringify(util.getUrddataString('team_id')))
                    //是否是push跳转
                    if(util.getUrddataString('team_id')){
                        //是
                        this.reportInfo.team_id = util.getUrddataString('team_id')
                        this.reportInfo.project_id = util.getUrddataString('project_id')
                    }else{
                        //正常urd跳转
                        if(!data){
                            widget.toast('登录超时,请重新登录')
                            commonPage.loadPageStatus('loadSuccess')
                            return
                        }
                        this.reportInfo.team_id = data.team_id
                        this.reportInfo.project_id = data.project_id
                    }
                    util.ajax({
                        url: '/form/info',
                        type: 'GET',
                        data: {
                            form_id: this.reportInfo.form_id,
                            team_id: this.reportInfo.team_id,
                            project_id: this.reportInfo.project_id
                        },
                        timeout: 10000,
                        success: (data) => {
                            // success
                            console.log(111+JSON.stringify(data.data.format_info))
                            if(data.errno == 0){
                                if(data.data.status != 1){
                                    widget.toast('该表单暂时无法提交，如有问题请与管理员联系')
                                    commonPage.goBack()
                                    return
                                }
                                data.data.format_info.forEach((obj) => {
                                    if(obj.type === 'Imageview'){
                                        obj.info.value = []
                                        obj.info.thumb_image_value = []
                                    }
                                })

                                this.reportInfo.info = data.data.format_info
                                this.desc = data.data.desc
                                document.title = data.data.title
                                this.getLocation()
                            }else{
                                // widget.toast('服务器异常')
                                widget.toast(data.errmsg)
                            }
                            
                            // alert(JSON.stringify(data))
                            commonPage.loadPageStatus('loadSuccess')
                        },
                        error: (xhr, status) => {
                            // error
                            widget.toast('服务器异常')
                            commonPage.loadPageStatus('loadSuccess')
                        },
                        noNetwork: () => {
                            // 无网络的回调
                            widget.toast('定位失败，请检查网络')
                            commonPage.loadPageStatus('loadSuccess')
                        }
                    })
                })
                

                commonPage.updateTitleBar({
                    backAction: 'checkChange',    // 点击返回按钮的动作（即回调函数名称）
                    // leftDisplay: false,            // 是否显示左按钮
                    // leftText: '',                // 左按钮文案
                    leftAction: 'checkChange',    // 点击左按钮的动作（即回调函数名称）
                    rightDisplay: true,            // 是否显示右按钮
                    rightText: '提交',            // 右按钮文案
                    rightAction: 'saveResume'    // 点击右按钮的文案（即回调函数名称）
                })
                window.saveResume = () => {
                    
                    // this.reportInfo.info.forEach((obj) => {
                    //     if(obj.type === 'Location'){
                    //         // obj.info.value = this.getLoc
                    //     }
                    // })
                    let isAllValid = this.valiDate();
                    if(isAllValid){
                        //提交数据
                        this.reportInfo.info.forEach((obj) => {
                            delete obj.isValid
                            // alert(obj.info.value[0].substr(0, util.baseImageDomain.length))
                            // if(obj.type == 'Imageview' && obj.info.value.length > 0){
                            //     obj.info.value = obj.info.value.map((url) => {
                            //         return url.substr(util.baseImageDomain.length-1)
                            //     })
                            //     alert(obj.info.value[0])
                            // }
                        })                        
                        // return
                        if(!ajaxEnd){
                            return
                        }
                        ajaxEnd = false

                        util.ajax({
                            url: '/form/report',
                            type: 'POST',
                            data: {
                                team_id: this.reportInfo.team_id,
                                project_id: this.reportInfo.project_id,
                                form_id: this.reportInfo.form_id,
                                info: this.reportInfo.info
                            },
                            timeout: 10000,
                            success: (data) => {
                                // success
                                if(data.errno == 0){
                                    //埋点
                                    let statisticsLog_data = {
                                        event_id: '数据表单上报页-提交',
                                        // event_label: data.event_label,(预留，现在不用传此参数)
                                        event_param: {
                                            ca_from: 'submit',
                                            project_id: this.reportInfo.project_id,
                                        }
                                    }
                                    KCApiApp.statisticsLog(statisticsLog_data)
                                    
                                    if(data.data.repeat_submit == 1){                                        
                                        clientUi.showDialog('提交成功', '', function(data){
                                            if(data.status == 1){
                                                if(clientUtil.OS() == 'android'){
                                                    commonPage.reloadPage()
                                                }else{
                                                    window.location.reload()
                                                }
                                            }else{
                                                commonPage.goBack(1)
                                            }
                                        },'继续填写','完成')
                                    }else{
                                        commonPage.goBack(1)
                                    }

                                }else if(data.errno == 22003 || data.errno == 22006){
                                    ajaxEnd = true
                                    widget.toast('提交失败，请稍后重试或联系管理员!')
                                }else if(data.errno == 22007){
                                    ajaxEnd = true
                                    widget.toast(data.errmsg)
                                    this.init();
                                }else{
                                    ajaxEnd = true
                                    widget.toast(data.errmsg)
                                }
                            },
                            error: (xhr, status) => {
                                ajaxEnd = true
                                // error
                                widget.toast('服务器异常')
                            },
                            noNetwork: () => {
                                ajaxEnd = true
                                // 无网络的回调
                                widget.toast('定位失败，请检查网络')
                            }
                        })
                    }
                }
                window.checkChange = () => {
                    let isEdit = this.reportInfo.info.some((obj) => {
                        return (obj.info.value && obj.info.value.length > 0) || (obj.info.value && obj.info.value.addr)
                    })
                    // alert(isEdit)
                    if(isEdit){
                        clientUi.showDialog('提醒', '当前表单已填写,是否放弃提交?', (status) => {
                            if(status.status === '1'){
                                commonPage.goBack()
                            }
                        })
                    }else{
                        commonPage.goBack()
                    }
                }
            },
            valiDate (){
                let isAllValid = false;
                for(let obj of this.reportInfo.info){
                    if(obj.type == 'Number' && obj.info.value && isNaN(obj.info.value)){
                        // alert(obj.info.value)
                        widget.toast(obj.info.title + ' 只允许输入纯数字!')
                        return
                    }
                    // return
                    if(obj.info.required == 1){
                        if(obj.type == 'Location'){
                            if(!obj.info.value.addr){
                                widget.toast(obj.info.title + ' 为必填项!')
                                isAllValid = false;
                                break;
                            }else{
                                isAllValid = true
                            }
                        }else if(obj.type == "Imageview"){
                            // console.log(JSON.stringify(obj))
                            if(!obj.info.thumb_image_value.length){
                                widget.toast(obj.info.title + ' 为必填项!')
                                isAllValid = false;
                                break;
                            }else if(obj.info.thumb_image_value.length < obj.info.check_guide.min){
                                widget.toast('请至少上传' + obj.info.check_guide.min + '张图片')
                                isAllValid = false;
                                break;
                            }else{
                                isAllValid = true
                            }
                        }else{
                            if(!(obj.info.value && obj.info.value.length)){
                                widget.toast(obj.info.title + ' 为必填项!')
                                isAllValid = false;
                                break;
                            }else{
                                isAllValid = true
                            }
                        }
                        
                    }else{
                        isAllValid = true
                    }
                }
                        

                // this.reportInfo.info.forEach((obj) => {
                //     if(obj.type === 'Date' || obj.type === 'Location' || obj.type === 'Imageview' || obj.type === 'Select'){
                //         if(obj.info.required){
                //             obj.isValid = obj.info.value && obj.info.value.length ? true : false;
                //         }else{
                //             obj.isValid = true;
                //         }
                //     }
                // })
                // let isAllValid = this.reportInfo.info.every((obj) => {
                //     return obj.isValid
                // })
                // console.log(this.reportInfo.info)
                // console.log(isAllValid)
                return isAllValid;
            },
            getLocation (){
                //定位
                    // data.citydomain        // 城市拼音简写
                    // data.city             // 城市名称
                    // data.cityid         // 城市ID
                // location.getCity((data) => {
                //     alert(JSON.stringify(data))
                // })
                // location.requestLocation((data) => {
                //     alert(JSON.stringify(data))
                // })
                    // data.lon     // 经度  
                    // data.lat     // 纬度
                commonPage.loadPageStatus('loading')

                util.requestPOI((data) => {
                    if(data.address){
                        this.reportInfo.info.forEach( (item) => {
                            if(item.type == 'Location'){
                                item.info.value = {
                                    "lat": data.lat,
                                    "lng": data.lon,
                                    "addr": data.address,
                                    'name':data.name
                                }
                                item.map_type=1//百度地图坐标
                            }

                        })
                        commonPage.loadPageStatus('loadSuccess')
                        // this.isTip = false;
                    }else{
                        commonPage.loadPageStatus('loadSuccess')
                        if(data&&data.error_msg){
                            widget.toast(data.error_msg)
                        }else{
                            widget.toast('定位失败，请检查网络')
                        }
                    }
                })
            },
            selectImage (index){
                // alert(JSON.stringify(this.reportInfo.info[index]))
                if(this.reportInfo.info[index].info.value.length < 20){
                    if(this.reportInfo.info[index].info.isSelectImg == 1){
                        clientUi.selectAndUploadImage((data) => {
                            // alert(111+JSON.stringify(data))
                            // alert(util.baseImageDomain + data.imageURL)
                            if(data.status == 1){
                                this.reportInfo.info[index].info.value.push('/' + data.imageURL)
                                this.reportInfo.info[index].info.thumb_image_value.push(util.baseImageDomain + data.imageURL)
                            }
                            
                        })
                    }else{
                        clientUi.invokeCamera((data) => {
                            // alert(222+JSON.stringify(data))
                            if(data.status == 1){
                                this.reportInfo.info[index].info.value.push('/' + data.imageURL)
                                this.reportInfo.info[index].info.thumb_image_value.push(util.baseImageDomain + data.imageURL)
                            }
                            
                            // alert(JSON.stringify(this.reportInfo.info[index].info.value))
                        })
                    }
                }else{
                    widget.toast('已达上传上限')
                }
            },
            pictureOperationDialog (par_index, index){
                clientUi.pictureOperationDialog('title', this.reportInfo.info[par_index].info.thumb_image_value, index, () => {
                    this.reportInfo.info[par_index].info.value.splice(index, 1)
                    this.reportInfo.info[par_index].info.thumb_image_value.splice(index, 1)
                    // alert(JSON.stringify(this.reportInfo.info[par_index].info.value))
                })
            },
            // 更新数据
            updateDate(data){
                if(data){
                    let key = data.key
                    let value = data.value
                    switch(key){ 
                            //更新二维码信息
                        case 'code':
                            this.reportInfo.info.forEach((obj) => {
                                if(obj.type === 'SingleText'){
                                    if(obj.id == value.formsingle_id){
                                        let scanResult = value.code
                                        let str = 'http://www.mobike.com/download/app.html'
                                        let isContains = new RegExp(str).test(scanResult)   
                                        if(isContains){
                                            let beginIndex = scanResult.indexOf('=')
                                            let endIndex = scanResult.indexOf('_')
                                            obj.info.value = scanResult.substring(beginIndex+1,endIndex)
                                        }else{
                                            obj.info.value = value.code
                                        }
                                    }
                                }
                            })
                            break
                        default:
                            break
                    }
                }
            },
            //反馈入口
            feedBack (){
                teamApi.showFeedback()
            }
        },
        created(){
            this.init();
            window.loadData = this.updateDate
            
        }
        
    }

    
</script>

<!-- CSS 样式 -->
<style src="../../node_modules/weui/dist/style/weui.css"></style>
<style type="text/css">
    html {
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    }
    html body{
        /*background-color: #fff;*/
        background-color: #f2f2f2;
    }
    div.weui-cells{
        margin-top:0px;
        font-size: 15px;
        
    }
    div.weui-cell{
        padding-top: 14px;
        padding-bottom: 14px;
    }
    div.comp-wrap{
        background-color: #f2f2f2;
        /*background-color: #fff;*/
        padding-top: 0.1px;
    }
    div.border-top{
        /*border-top:12px solid #f2f2f2;*/
        /*position: relative;*/
        /*padding:0.1px;*/
    }
    #items div:first-child div.border-top{
        border-top: 0;
    }
    div.black{
        color: rgb(51,51,51);
        font-size: 16px;
        margin-bottom: 0px;
        margin-top: 16px;
        line-height: 1.375;
    }
    div.border-top div.weui-cells__tips{
        margin-bottom: 6px;
        color: rgb(102,102,102);
        font-size: 14px;
        margin-top: 0;
        line-height: 1.375;
    }
    li.img{
        overflow: hidden;
        width:60px;
        height:60px;
        /*box-sizing: border-box;
        margin-right:0;
        padding-right: 9px;*/
        margin-right: 8px;
        margin-bottom: 8px;
    }
    li.img img{
        /*width:100%;*/
        width: 60px;
        /*height: 60px;*/
    }
    div.weui-uploader__input-box{
        width:60px;
        height:60px;
        margin-right: 8px;
        margin-bottom: 8px;
    }
    div.pad-left-0{
        padding-left: 0;
    }
    div.pad-lr{
        padding:0px 12px;
    }
    div.pad-tb{
        padding:24px 12px 32px;
    }
    div.weui-uploader__bd{
        margin:0;
    }
    div.bg_color{
        background-color: #f2f2f2;
        margin:0;
        /*margin-top:7px;*/
        /*padding-top: 18px;
        padding-bottom: 4px;*/
        padding:10px 12px;
        line-height: 1.3;

        text-align: center;
    }
    div.weui-textarea-counter,div.weui-uploader__info{
        font-size: 12px;
        color: #999;
    }
    div.weui-cells:before{
        border-top: 1px solid #e5e5e5;
        /*left:12px;*/
        left:0px;
    }
    div.weui-cells.left_0:before{
        left:0;
    }
    div.weui-cells:after{
        border-bottom: 1px solid #e5e5e5;
    }
    div.weui-cell a.weui-btn_default{
        background-color: #fff;
        border:none;
        color:#4499ff;
        padding-right: 4px;
    }
    div.weui-cell a.weui-btn_default:active{
        background-color: #fff;
    }
    .padding-12{
        padding-left: 12px;
        font-size: 14px;
    }
    .isTip{
        color: #ccc;
    }
    p.weui-uploader__title{
        color:rgb(51,51,51);
    }
    p.isTitle{
        font-size: 16px;
    }
    input.weui-input{
        font-size: 16px;
    }
    
    input{
        -webkit-appearance: none;
    }
    textarea.weui-textarea{
        font-size: 16px;
    }
    div.isValue p{
        font-size: 16px;
    }
    div.bg_f2{
        background-color: #f2f2f2;
        padding:0.1px;
    }
    div.img_cont{
        position: absolute;
        right:12px;
        bottom:12px;
        color: rgb(153,153,153);
        font-size: 14px;
    }
    span.required_icon{
        /*display: inline-block;
        width:7px;
        height:7px;
        margin-left: 5px;
        margin-bottom: 2px;
        background-image: url(../../static/imgs/required.png);*/
        font-size: 14px;
        color: rgb(153,153,153);
    }
</style>
<style>
    .padding{
        height: 108px;
        width: 100%;
        display: inline-block;
    }
    .addr_name{
        font-size: 16px;
        color: #333333;
        line-height: 24px;
        font-weight: bold;
        margin: 10px 0px 5px 0px;
        height: 24px;
    }
    .addr_detail{
        font-size: 14px;
        color: #999999;
        line-height: 20px;
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
        width: 96%;
    }
    .error_tips{
        display: inline-block;
    }
    .error_text{
        height: 20px;
        font-size: 14px;
        color: #F79F8B;
        letter-spacing: 0;
        line-height: 20px;
    }
    .errorIcon{
        width: 5px;
        height: 5px;
        background-color: #F79F8B;
        display: inline-block;
        border-radius: 6px;
        margin-right: 5px;
        margin-bottom: 3px;
    }
    .relacation{
        width: 60px;
        font-size: 14px;
        color: #4990E2;
        letter-spacing: 0;
        line-height: 22px;
        display: inline-block;
        position: absolute;
        right: 22px;
        bottom: 0px;
    }
    .feedback-box{
        position: absolute;
        right: 12px;
        top: 16px;
    }
    .feedback-icon{
        width: 12px;
        height: 12px;
    }
    .feedback-text{
        font-size: 14px;
        height: 22px;
        color: #4990E2;
        letter-spacing: 0;
        line-height: 22px; 
    }
    .location_tip{
        margin-top: 14px;
        width: 100%;
        height: 22px;
        position: relative;
    }
</style>


